package com.hmdp.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.RedisScript;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redisson;
    @Autowired
    private SeckillVoucherMapper seckillVoucherMapper;
    @Autowired
    private RedisScript redisScript;

    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    //创建线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct //创建完对象之后就执行这个任务
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    String queueName = "steam.orders";
    //线程任务
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true){
                try {
                    //1.获取消息队列里面的订单信息  XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            org.springframework.data.redis.connection.stream.Consumer.from("g1", "c1"),
                                    StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                                    StreamOffset.create(queueName, ReadOffset.lastConsumed())
                            );
                    //2.判断消息获取是否成功
                    if (list.isEmpty() || list == null){
                        //消息获取失败
                        continue;
                    }
                    //3.解析消息中的订单信息
                    MapRecord<String, Object, Object> recode = list.get(0);
                    Map<Object, Object> map = recode.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(map, new VoucherOrder(), true);
                    //4.创建订单
                    handlerVoucherOrder(voucherOrder);
                    //5.ACK确认收到信息
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",recode.getId());
                }catch (Exception e){
                    //说明没有进行ACK确认收到信息
                    log.error("处理订单异常",e);
                    handlerPandingList();
                }

            }
        }
    }

    private void handlerPandingList() {
        while (true){
            try {
                //1.获取pendingList中的订单信息    XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                List<MapRecord<String, Object, Object>> record = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0"))
                );
                //2.进行获取判断
                if (record.isEmpty() || record == null){
                    //如果没有获取到信息，说明没有错误
                    break;
                }
                //3.获取订单信息
                MapRecord<String, Object, Object> entries = record.get(0);
                Map<Object, Object> map = entries.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(map, new VoucherOrder(), true);

                //4.获取成功直接下单
                //4.创建订单
                handlerVoucherOrder(voucherOrder);
                //5.ACK确认收到信息
                stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());
            }catch (Exception e){
                //如果出现错误直接进行自调用
                handlerPandingList();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }

        }
    }

//    //线程任务
//    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while (true){
//                try {
//                    //1.获取消息队列里面的订单信息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //2.创建订单
//                    handlerVoucherOrder(voucherOrder);
//                }catch (Exception e){
//                    log.error("处理订单异常",e);
//                }
//
//            }
//        }
//    }

    private IVoucherOrderService proxy;
    /**
     * 创建订单
     * @param voucherOrder
     */
    private void handlerVoucherOrder(VoucherOrder voucherOrder){
        Long userId = voucherOrder.getUserId();
        RLock lock = redisson.getLock("lock:order:" + userId);
        //6.获取锁
        Boolean isLock = lock.tryLock();
        if (!isLock) {
            //如果不能够获取锁，直接返回报错即可
            log.error("不允许重复下单");
            return ;
        }
        try {
            //自调用，事务不会生效,必须使用代理
            proxy.createVoucherOrder(voucherOrder);
        }finally {
            //手动释放锁
            lock.unlock();
        }
    }

    /**
     * 限时秒杀
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {

        DefaultRedisScript SECKILL_SCRIPT = redisScript.getScript("seckill.lua");

        //注册lura脚本
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setResultType(Long.class);
        SECKILL_SCRIPT.setLocation(new org.springframework.core.io.ClassPathResource("seckill.lua"));

        long orderId = redisIdWorker.nextId("order");
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        //2.运行lura脚本
        Long execute = (Long) stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.EMPTY_LIST,
                voucherId.toString(),
                userId.toString(),
                orderId
        );
        //3.将返回的Long类型进行转换，方便后面的比对
        int i = execute.intValue();
        //4.进行逻辑判断
        if (i == 1){
            return Result.fail("库存不足");
        } else if (i == 2) {
            return Result.fail("一人仅限购一份");
        }

        return Result.ok("ok");
    }



//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.先查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀时间是否开始
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            //尚未开始
//            return Result.fail("秒杀尚未开始");
//        }
//        //3.判断秒杀是否以及结束
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            //已经结束
//            return Result.fail("秒杀以及结束");
//        }
//        //4.判断库存是否充足
//        if (voucher.getStock()<1) {
//            System.out.println(voucher.getStock());
//            //库存不够
//            return Result.fail("库存不足");
//        }
//        //一人一单的问题：悲观锁;
//        Long userId = UserHolder.getUser().getId();
//        Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//        if (count > 0) {
//            return Result.fail("每人限购一单");
//        }
//        //减小锁的执行范围，提高性能；在微服务里面，jvm不同就不管用了;不加intern就是白费劲，toString底层会创建新对象，就算id一样也会判断为不同线程
//        //5.新建锁对象
//        RLock lock = redisson.getLock("lock:order:" + userId);
//        //6.获取锁
//        Boolean isLock = lock.tryLock();
//        if (!isLock) {
//            //如果不能够获取锁，直接返回报错即可
//            return Result.fail("不能够尽心重复购买");
//        }
//        try {
//            //自调用，事务不会生效,必须使用代理
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId,userId);
//        }finally {
//            //手动释放锁
//            lock.unlock();
//        }
//
//    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder){
        Long userId = UserHolder.getUser().getId();
        //5.扣减库存；乐观锁  ； 只要库存大于零就允许减
        int count = query().eq("user_id",userId).eq("voucher_id",voucherOrder.getVoucherId()).count();
        if (count < 1){
            log.error("用户已经购买了一次");
            return;
        }

        //扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock -1")
                .eq("voucher_id",voucherOrder.getVoucherId()).gt("stock",0)
                .update();
        if (!success){
            log.error("库存不足");
            return;
        }

        //创建订单
        save(voucherOrder);
    }
}
